﻿using System;
using System.Configuration;
using System.Linq;
using System.Web.Http;
using log4net;
using Matrix.Common.Utility;
using Matrix.MaKaYunShang.BLL;

namespace Matrix.MaKaYunShang.McMagWeb.Controllers.APIs
{
    // Message Notification API
    public class NotificationsController : ApiController
    {
        private readonly ILog _fileLog = LogManager.GetLogger(typeof(NotificationsController));

        [HttpGet]
        public bool PushNotification(int shopId, int pushingMsgType, string orderNo, string wxUserOpenId, string mcAccountId)
        {
            var checkResult = CheckPermission("OrderApiController | PushNotification");
            if (!checkResult)
            {
                return false;
            }

            McMessagesBLL.Instance.PushingMsg(shopId, pushingMsgType, orderNo, wxUserOpenId, mcAccountId);

            return true;
        }

        /// <summary>
        /// 检查接口调用权限
        /// </summary>
        /// <returns></returns>
        protected bool CheckPermission(string interfaceEntryName)
        {
            var strClientIp = IpHelper.IPAddress;
            _fileLog.Info("NotificationsController | " + interfaceEntryName + " | Client Ip: " + strClientIp +
                          " | Called time: " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));

            var strLimitIpSwitch = ConfigurationManager.AppSettings["LimitIpSwitch"];
            if (strLimitIpSwitch == "0")
            {
                return true;
            }

            var strAccessIp = ConfigurationManager.AppSettings["AccessIp"];
            if (string.IsNullOrWhiteSpace(strAccessIp))
            {
                return false;
            }

            var arAccessIp = strAccessIp.Split(',');
            var bCheck = arAccessIp.Any(accessIp => strClientIp == accessIp);

            if (!bCheck)
            {
                _fileLog.Error("NotificationsController | " + interfaceEntryName + " | Error: Invalid Ip - " + strClientIp);
            }

            return bCheck;
        }

    }

}